package leetcode_day._2022._202201._2131;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yzh
 * @version 1.0
 * @date 2022/1/26 9:24
 * 检测正方形
 * 算法：哈希表
 * 哈希表套哈希表，key 为 x，value 为一个 map
 * 里面的 map 的 key 为 y，value 为 y 的个数
 */
public class _26_2013 {

    class DetectSquares {
        Map<Integer, Map<Integer, Integer>> map;
        public DetectSquares() {
            map = new HashMap<>(16);
        }

        public void add(int[] point) {
            Map<Integer, Integer> tmp = map.getOrDefault(point[0], new HashMap<>(16));
            tmp.put(point[1], tmp.getOrDefault(point[1], 0) + 1);
            map.put(point[0], tmp);
        }

        public int count(int[] point) {
            int x = point[0], y = point[1];
            Map<Integer, Integer> yCnt = map.getOrDefault(x, new HashMap<>(16));
            int ans = 0;
            for (Integer ny : yCnt.keySet()) {
                if (y == ny) continue;
                int len = y - ny, c1 = yCnt.get(ny);
                int[] nums = new int[]{x + len, x - len};
                for (int num : nums) {
                    Map<Integer, Integer> tmp = map.getOrDefault(num, new HashMap<>(16));
                    int c2 = tmp.getOrDefault(y, 0), c3 = tmp.getOrDefault(ny, 0);
                    ans += c1 * c2 * c3;
                }
            }
            return ans;
        }
    }

}
